﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Common;
using Models;
using Senparc.Weixin;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using Senparc.Weixin.MP.Containers;

namespace Web.Controllers.View
{
    public class RegisterController : Controller
    {
        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="code">微信回调参数</param>
        /// <returns></returns>
        public ActionResult Index(string code)
        {
            // 获取当前页面地址作为回调地址
            var redirectUrl = WebHelper.GetUrl();

            #region 微信授权登录
            if (string.IsNullOrEmpty(code))
            {
                var wechatAuthorizeUrl = OAuthApi.GetAuthorizeUrl(WxConfig.APPID, redirectUrl
                    , "STATE", OAuthScope.snsapi_userinfo);
                return Redirect(wechatAuthorizeUrl);
            }

            var accesstokenresult = OAuthApi.GetAccessToken(WxConfig.APPID, WxConfig.APPSECRET, code);
            var oauthuserinfo = OAuthApi.GetUserInfo(accesstokenresult.access_token, accesstokenresult.openid);
            #endregion

            #region 发送模板消息
            var accesstoken = AccessTokenContainer.GetAccessToken(WxConfig.APPID);
            var openId = oauthuserinfo.openid;
            var templateId = "htyRDiuwdifULIYOjARaM8n8sTbcetsN7zDL11Jyj_M";
            var linkUrl = "";    //点击详情后跳转后的链接地址，为空则不跳转  

            //为模版中的各属性赋值  
            var templateData = new RegisterSuccess()
            {
                first = new TemplateDataItem(string.Format("恭喜您，成功注册Hnabc.cn会员！"), "#CC0033"),
                keyword1 = new TemplateDataItem(oauthuserinfo.nickname, "#99CC00"),
                keyword2 = new TemplateDataItem(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "#99CC00"),
                keyword3 = new TemplateDataItem(oauthuserinfo.country + "-" + oauthuserinfo.city, "#99CC00"),
                remark = new TemplateDataItem("如需帮助，请在公众号留言！", "#CC0033")
            };

            var sendResult =
                   TemplateApi.SendTemplateMessage(accesstoken, openId, templateId, linkUrl, templateData);
            if (sendResult.errcode != ReturnCode.请求成功)
            {
                return Content(sendResult.errmsg);
            }
            #endregion

            return View(oauthuserinfo);
        }

    }
}
